<!--
  * 库存信息表（单租户版）
  *
  * @Author:    ADog
  * @Date:      2025-09-20 15:55:03
  * @Copyright  1.0
-->
<template>
  <div>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="关键字查询" class="smart-query-form-item">
          <a-input style="width: 200px" v-model:value="queryForm.keywords" placeholder="关键字查询" />
        </a-form-item>
        <a-form-item label="库存数量" class="smart-query-form-item">
          <a-input style="width: 200px" v-model:value="queryForm.stockQuantity" placeholder="库存数量" />
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" class="smart-margin-left10">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
      <!---------- 表格操作行 begin ----------->
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button @click="showForm" type="primary" size="small">
            <template #icon>
              <PlusOutlined />
            </template>
            新建
          </a-button>
          <a-button @click="confirmBatchDelete" type="primary" danger size="small" :disabled="selectedRowKeyList.length == 0">
            <template #icon>
              <DeleteOutlined />
            </template>
            批量删除
          </a-button>
        </div>
        <div class="smart-table-setting-block">
          <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
        </div>
      </a-row>
      <!---------- 表格操作行 end ----------->

      <!---------- 表格 begin ----------->
      <a-table
        size="small"
        :scroll="{ y: 800 }"
        :dataSource="tableData"
        :columns="columns"
        rowKey="stockId"
        bordered
        :loading="tableLoading"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      >
        <template #bodyCell="{  record, column }">


          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="showForm(record)" type="link">编辑</a-button>
              <!--            状态0代表是审批人-->
              <a-button  @click="prove(record)" v-if="record.assigneeName!==null" type="link">审批</a-button>
              <a-button @click="showProcess(record)" type="link">查看流程进度</a-button>

            </div>
          </template>
        </template>
      </a-table>
      <!---------- 表格 end ----------->

      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="queryData"
          @showSizeChange="queryData"
          :show-total="(total) => `共${total}条`"
        />
      </div>

    </a-card>
  </div>



  <a-modal v-model:open="visiblleFlag" title="流程审批">
  <div>
    <a-button @click="confirmApprove(currentRecord)" type="primary">审批通过</a-button>
    <a-button  type="primary"  class="smart-margin-left20">审批驳回</a-button>
  </div>
  </a-modal>
  <!-- 流程进度弹窗 -->
  <a-modal v-model:open="visiblleFlag2" title="流程进度">
    <div style="height: auto; margin-bottom: 30px; text-align: center;">
      <img
        :src="flowImageUrl"
        alt="流程进度图"
        style="max-width: 100%; height: auto;"
      @error="() => { flowImageUrl = 'https://via.placeholder.com/600x300?text=加载失败' }"
      />
    </div>
  </a-modal>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import {flowDeployApi} from '/src/api/business/workflowtodo/work-flow-todo-api.js'
import { stockApi } from '/@/api/business/wms/stock/stock-api';
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { smartSentry } from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '任务ID',
    dataIndex: 'taskId',
    ellipsis: true,
  },
  {
    title: '任务名称',
    dataIndex: 'taskName',
    ellipsis: true,
  },
  {
    title: '任务定义Key',
    dataIndex: 'taskDefKey',
    ellipsis: true,
  },
  {
    title: '处理人ID',
    dataIndex: 'assigneeId',
    ellipsis: true,
  },
  {
    title: '审批人姓名',
    dataIndex: 'assigneeName',
    ellipsis: true,
  },
  {
    title: '流程定义ID',
    dataIndex: 'procDefId',
    ellipsis: true,
  },
  {
    title: '流程定义Key',
    dataIndex: 'procDefKey',
    ellipsis: true,
  },
  {
    title: '流程定义名称',
    dataIndex: 'procDefName',
    ellipsis: true,
  },
  {
    title: '发起人姓名',
    dataIndex: 'startUserName',
    ellipsis: true,
  },
  {
    title: '历史流程实例ID',
    dataIndex: 'hisProcInsId',
    ellipsis: true,
  },
  {
    title: '审批人状态',
    dataIndex: 'status',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 90,
  },
]);


// ---------------------------- 查询数据表单和方法 ----------------------------

const queryFormState = {
  keywords: undefined, //关键字查询
  stockQuantity: undefined, //库存数量
  pageNum: 1,
  pageSize: 10,
};
// 查询表单form
const queryForm = reactive({ ...queryFormState });
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery() {
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}

// 搜索
function onSearch(){
  queryForm.pageNum = 1;
  queryData();
}

// 查询数据
async function queryData() {
  tableLoading.value = true;
  try {
    let queryResult = await flowDeployApi.queryMyTask(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}


onMounted(queryData);

// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();

function showForm(data) {
  formRef.value.show(data);
}

// ---------------------------- 单个删除 ----------------------------
//确认删除
function onDelete(data){
  Modal.confirm({
    title: '提示',
    content: '确定要删除选吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestDelete(data);
    },
    cancelText: '取消',
    onCancel() {},
  });
}

//请求删除
async function requestDelete(data){
  SmartLoading.show();
  try {
    let deleteForm = {
      goodsIdList: selectedRowKeyList.value,
    };
    await stockApi.delete(data.stockId);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

// 批量删除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要批量删除这些数据吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestBatchDelete();
    },
    cancelText: '取消',
    onCancel() {},
  });
}

//请求批量删除
async function requestBatchDelete() {
  try {
    SmartLoading.show();
    await stockApi.batchDelete(selectedRowKeyList.value);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
//  审批通过
const visiblleFlag = ref(false);
async function prove(record){
  currentRecord.value = record; // 保存当前任务的完整数据
  visiblleFlag.value = true;
}
// 保存当前需要审批的任务记录
const currentRecord = ref(null);
async function confirmApprove(currentRecord){
  visiblleFlag.value = false;
  await flowDeployApi.completeTask(currentRecord.taskId);
  queryData() ;
}

// 定义基础路径
const flowImageUrl = ref(''); // 新增：存储流程图图片地址
const visiblleFlag2= ref(false);
const procInsId = ref(null);
async function showProcess(record) {
  visiblleFlag2.value = true;
  procInsId.value = record.procInsId;
  flowImageUrl.value = ''; // 重置，避免旧图残留

  try {
    // 接口直接返回 Blob URL（如 blob:http://xxx），直接赋值
    const blobUrl = await flowDeployApi.downloadFlowActiveImg(record.procInsId);
    console.log('流程图Blob URL：', blobUrl); // 确认是类似 blob:xxx 的地址
    flowImageUrl.value = blobUrl; // 赋值给响应式变量
  } catch (error) {
    console.error('加载流程图失败：', error);
    message.error('加载流程图失败，请重试');
    flowImageUrl.value = 'https://via.placeholder.com/600x300?text=加载失败'; // 错误兜底
  }
}
</script>
